package cn.stylefeng.guns.modular.demo.excel.listener.peisong;

import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.dao.entity.SellDoc;
import cn.stylefeng.guns.dao.entity.SellDocDetail;
import cn.stylefeng.guns.dao.service.ISellDocDetailService;
import cn.stylefeng.guns.dao.service.ISellDocService;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.SellDocExcelDetailVO;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.SellDocExcelVO;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 阿斯利康采购数据
 */
@Slf4j
public class SellDocDetailListener implements ReadListener<SellDocExcelDetailVO> {


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    private List<SellDocDetail> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    private List<String> errorList;
    ISellDocDetailService sellDocDetailService;


    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param sellDocDetailService
     */
    public SellDocDetailListener(ISellDocDetailService sellDocDetailService, List<String> errorList) {
        this.sellDocDetailService = sellDocDetailService;
        this.errorList = errorList;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(SellDocExcelDetailVO data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        SellDocDetail sellDocDetail = o2o(data);

//        if (keyList.contains(key)) {
//            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "同一批次内有相同的商品 批次号:" + batch + ",商品名称:" + commodityName);
//        }
//        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, goodsCode));
//        if (Objects.isNull(goods)) {
//            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "商品不存在" + goodsCode);
//        }

//        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery().eq(Supplier::getName, supplierName));
//        if (Objects.isNull(supplier)) {
//            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "供应商不存在" + supplierName);
//        }


        cachedDataList.add(sellDocDetail);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private SellDocDetail o2o(SellDocExcelDetailVO sellDocExcelDetailVO) {
        if (sellDocExcelDetailVO == null) {
            return null;
        }
        SellDocDetail sellDocDetail = new SellDocDetail();
        sellDocDetail.setTime(sellDocExcelDetailVO.getSellDate().getTime());
        sellDocDetail.setGoodsCode(sellDocExcelDetailVO.getGoodsCode());

        sellDocDetail.setStoCode(sellDocExcelDetailVO.getStoCode());

        sellDocDetail.setNum(sellDocExcelDetailVO.getNum());
        sellDocDetail.setPrice1(sellDocExcelDetailVO.getPrice1());
        sellDocDetail.setPrice2(sellDocExcelDetailVO.getPrice2());
        sellDocDetail.setPrice3(sellDocExcelDetailVO.getPrice3());
        sellDocDetail.setPrice4(sellDocExcelDetailVO.getPrice4());
        sellDocDetail.setPrice5(sellDocExcelDetailVO.getPrice5());
        sellDocDetail.setData(JSON.toJSONString(sellDocExcelDetailVO));
        return sellDocDetail;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            errorList.add("第" + excelDataConvertException.getRowIndex() + "行，第" + excelDataConvertException.getColumnIndex() + "列解析异常，数据为:" + excelDataConvertException.getCellData());
        }

        if (exception instanceof BusinessException) {
            errorList.add(exception.getMessage());
        } else {
            log.info("数据错误解析错误", exception);
        }

    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        try {
            log.info("{}条数据，开始存储数据库！", cachedDataList.size());
            sellDocDetailService.saveBatch(cachedDataList);
            log.info("存储数据库成功！");
        } catch (Exception e) {
            log.info("数据错误", e);
            throw e;
        }
    }

}
